<template>
    <div>
        <div class="content-box">
            <div class="search-container">
                <div class="form-content">
                    <el-form :inline="true" ref="filterFormRef" :model="filter" class="demo-form-inline">
                        <el-form-item label="角色名称" prop="roleName">
                            <el-input v-model.trim="filter.roleName" maxlength="200" placeholder="请输入角色名" clearable/>
                        </el-form-item>
                        <el-form-item label="角色代码" prop="roleCode">
                            <el-input v-model.trim="filter.roleCode" maxlength="200" placeholder="请输入角色代码" clearable/>
                        </el-form-item>
                        <el-form-item label="状态" prop="enabled">
                            <el-select v-model="filter.enabled" placeholder="全部" clearable>
                                <el-option label="全部" value="" />
                                <el-option label="启用" :value="true" />
                                <el-option label="禁用" :value="false" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="创建时间">
                            <DateRange
                                ref="dateRangeRef"
                                :isTimeStamp="true"/>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="search-btn">
                    <el-button type="primary" @click="getFilterParams">查询</el-button>
                    <el-button @click="resetForm(filterFormRef)">重置</el-button>
                </div>
            </div>
            <div class="operate-btn" v-if="btnAuthMap['midrange:front:role:create']">
                <el-button type="primary" :icon="Plus" @click="createRole()">新增</el-button>
            </div>
            <div>
                <!-- 列表 -->
                <table-wrap hideHeader title="角色列表" :total="total"
                        :loading="loading" v-model:pageSize="requestData.pageSize"
                        v-model:pageIndex="requestData.pageIndex" :tableData="tableData" @request-list="getList">
                        <el-table-column label="序号" align="center" fixed="left" min-width="60" show-overflow-tooltip>
                            <template #default="scope">
                                <div>{{(requestData.pageIndex - 1 )*requestData.pageSize+scope.$index+1}}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="roleName" min-width="140" label="角色名" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="roleCode" min-width="140" label="角色代码" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="roleCode" min-width="140" label="所属场景" show-overflow-tooltip>
                            <template #default="scope">
                                <span v-for="(scene, index) in scope.row.sceneVOS" :key="scene.id">{{ index? '、'+scene.sceneName:scene.sceneName }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="comments" min-width="140" label="角色描述" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="created" min-width="140" label="创建时间" show-overflow-tooltip>
                            <template #default="scope">
                                <span>{{ dayjs(scope.row.gmtCreate).format('YYYY-MM-DD HH:mm:ss') }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" min-width="100" label="状态" show-overflow-tooltip>
                            <template #default="scope">
                                <el-switch
                                    v-model="scope.row.enabled"
                                    width="50px"
                                    class="ml-2"
                                    inline-prompt
                                    active-text="启用"
                                    inactive-text="禁用"
                                    @change="OperateRole(scope.row)"
                                    :disabled="!btnAuthMap['midrange:front:role:status']"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="150" fixed="right" align="center" v-if="getOpBtnLen(['midrange:front:role:edit', 'midrange:front:role:asign', 'midrange:front:role:delete'])">
                            <template #default="scope">
                                <el-button type="primary" v-if="btnAuthMap['midrange:front:role:edit']" link @click="createRole(scope.row)">编辑</el-button>
                                <el-button type="primary" v-if="btnAuthMap['midrange:front:role:asign']" link @click="assignPermission(scope.row)">分配权限</el-button>
                                <!-- <el-button type="primary" v-if="btnAuthMap['midrange:front:role:delete']" link @click="delFunc(scope.row)">删除</el-button> -->
                            </template>
                        </el-table-column>
                </table-wrap>
            </div>
        </div>
        <AddRole v-if="roleDialogParams.show" :dialogParams="roleDialogParams" :role="currentRole" @dialog:close="closeRoleDialog" @dialog:confirm="confirmRoleDialog"></AddRole>
        <AssignPermission v-if="permissionDialogParams.show" :dialogParams="permissionDialogParams" :role="currentRole" @dialog:close="closePermissionDialog" @dialog:confirm="confirmPermissionDialog"></AssignPermission>
    </div>
</template>
<script>
    import { reactive, ref, onMounted } from 'vue'
    import { useStore } from 'vuex'
    import { ElMessage } from 'element-plus'
    import DateRange from '@/components/date-range.vue';
    import TableWrap from '@/components/table-wrap/table-wrap.vue'
    import AddRole from './dialog/add-role.vue'
    import AssignPermission from './dialog/assign-permission.vue'
    import {
        Plus, Search
    } from '@element-plus/icons-vue'
    import Dialog from '@/lib/fn.js'
    import dayjs from 'dayjs'
    import { useBtnAuth } from '@/hooks/useBtnAuth.js'
    export default {
        name: 'role-list',
        components: { TableWrap, AddRole, AssignPermission, DateRange },
        setup() {
            const store = useStore()
            const filterFormRef = ref()
            const filter = reactive({
                roleName: null,
                roleCode: null,
                enabled: null
            })
            const dateRangeRef = ref(null)
            const { btnAuthMap, getOpBtnLen } = useBtnAuth()
            const keyword = ref('')
             const time = reactive({
                gmtCreateLt: null,
                gmtCreateGt: null
            })
            const multipleTable = ref()
            const tableData = ref([])
            const total = ref(0);
            const loading = ref(false);
            const requestData = ref({
                pageIndex: 1,
                pageSize: 10
            })
            const multipleSelection = ref([])
            // 新建角色参数
            const roleDialogParams = ref({
                show: false,
                title: '新增角色',
                width: '600px',
                showButton: true
            })
            const currentRole = ref()
            const getRowKeys = (row) => {
                return row.id;
            }
            const onSubmit = () => {
                console.log('submit!');
            };
            const getFilterParams = (val) => {
                requestData.value.pageIndex = 1
                let timeInfo = dateRangeRef.value.getDateRange()
                time.gmtCreateGt = timeInfo.startTime
                time.gmtCreateLt = timeInfo.endTime
                getList()
            }
            const resetForm = (formEl) => {
                if (!formEl) return
                formEl.resetFields()
                time.gmtCreateLt = null
                time.gmtCreateGt = null
                dateRangeRef.value.resetDateRange();
                getList()
            }
            // 列表
            const getList = () => {
                console.log(time, time.gmtCreateGt);
                loading.value = true;
                for(let key in filter) {
                    if(filter[key] === '') {
                        filter[key] = null
                    }
                }
                console.log(time, time.gmtCreateGt, time.gmtCreateLt);
                store.dispatch('proxyAction', {
                    name: 'frontRoleList',
                    data: {
                        ...filter,
                        ...requestData.value,
                        gmtCreateLt: time.gmtCreateLt,
                        gmtCreateGt: time.gmtCreateGt
                    }
                }).then((res) => {
                    if(res&&res.data) {
                        tableData.value = res.data.rows || [];
                        tableData.value.forEach((item) => {
                            item.sceneKeys = []
                            if(item.sceneVOS) {
                                item.sceneVOS.forEach((value) => {
                                    item.sceneKeys.push(value.sceneKey)
                                })
                            }
                        })
                        total.value = res.data.total;
                    }
                }).finally(() => {
                    loading.value = false;
                })
            }
            // 新建角色
            const createRole = (item) => {
                roleDialogParams.value.show = true;
                if (item) {
                    roleDialogParams.value.title = '编辑角色'
                    currentRole.value = item
                } else {
                    currentRole.value = null
                }
            }
            // 启用用户
            const enableRole = (id, enabled) => {
                store.dispatch('proxyAction', {
                    name: 'frontEnableRole',
                    data: {
                        id, 
                        enabled
                    }
                }).then((res) => {
                    console.log('res', res)
                    store.dispatch('message', {
                        message: enabled?'已启用':'已禁用'
                    })
                }, (error) => {
                    console.log('error', error)
                })
            }
            const OperateRole = (item) => {
                console.log('item', item)
                Dialog.Confirm(function(){
                    enableRole(item.id, item.enabled)
                }, item.enabled?'启用后，拥有此角色的用户将获得操作权限，是否确认启用？':'禁用后，拥有此角色的用户将失去操作权限，是否确认禁用？', item.enabled?'确定启用':'确定禁用', function(){
                    item.enabled = !item.enabled
                })()
            }
            // 关闭新建角色对话框回调
            const closeRoleDialog = () => {
                roleDialogParams.value.show = false;
            }
            // 确认新建角色对话框回调
            const confirmRoleDialog = () => {
                roleDialogParams.value.show = false;
                getList()
            }
            // 分配权限对话框参数
            const permissionDialogParams = ref({
                show: false,
                title: '分配权限',
                width: '900px',
                showButton: true,
                cancelText: '关闭',
                hasOk: false
            })
            // 分配权限
            const assignPermission = (item) => {
                permissionDialogParams.value.show = true;
                currentRole.value = item
            }
            // 关闭分配权限对话框回调
            const closePermissionDialog = () => {
                permissionDialogParams.value.show = false;
                currentRole.value = null
            }
            // 分配对话框confirm回调
            const confirmPermissionDialog = () => {
                permissionDialogParams.value.show = false;
                currentRole.value = null
            }
            
            const delFunc = (item) => {
                Dialog.Confirm(function(){
                    store.dispatch('proxyAction', {
                        name: 'frontDelRole',
                        data: {
                            id: item.id
                        }
                    }).then((res) => {
                        console.log('res', res)
                        store.dispatch('message', {
                            message: '已删除'
                        })
                        getList()
                    }, (error) => {
                        console.log('error', error)
                    })
                }, '确认要删除这个角色吗？', '确认删除')()
            }
            onMounted(() => {
                getList()
            })

            return {
                filterFormRef,
                filter,
                keyword,
                time,
                dateRangeRef,
                btnAuthMap,
                getOpBtnLen,
                tableData,
                total,
                requestData,
                loading,
                multipleSelection,
                currentRole,
                onSubmit,
                Search,
                Plus,
                dayjs,
                getRowKeys,
                getFilterParams,
                resetForm,
                getList,
                createRole,
                OperateRole,
                roleDialogParams,
                closeRoleDialog,
                confirmRoleDialog,
                permissionDialogParams,
                assignPermission,
                closePermissionDialog,
                confirmPermissionDialog,
                delFunc
            };
        }
    };
</script>
<style scoped lang="scss">
.content-box {
    min-height: calc(100vh - 200px);
    padding: 20px;
}
.w200 {
    width: 200px;
}
.mr0 {
    margin-right: 0;
}
.mt20 {
    margin-top: 20px;
}
.search-input {
    width: 270px;
}
.filter-box {
    display: flex;
    .el-form {
        flex: 1
    }
}
</style>